package com.task.scheduling.controller;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 此类用来捕获controller抛出的运行时异常
 * @author zhouliangliang
 *
 */
@ControllerAdvice
public class ExceptionHandler {

	private Logger log = LoggerFactory.getLogger(ExceptionHandler.class);
	
	/**
	 * 此类主要进行两个操作
	 * 1.打印请求参数
	 * 2.打印错误日志
	 * @param req
	 * @param e
	 * @return
	 */
	@org.springframework.web.bind.annotation.ExceptionHandler(RuntimeException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	public String serverErrorHandler(HttpServletRequest req, RuntimeException e) {
		try{
			Enumeration<String> attributes = req.getParameterNames();
			//迭代记录请求参数
			while (attributes.hasMoreElements()) {
				String attributeName = attributes.nextElement();
				String attributeValue = req.getParameter(attributeName);
				log.error(attributeName + ":" + attributeValue);
			}
			//记录错误日志
			log.error("请求参数为:" + req.getQueryString());
			log.error("请求地址为:" + req.getRequestURL().toString());
			log.error("错误详细信息" + e.getMessage(), e);
			return "redirect:/500";
		} catch (Exception ex) {
			log.error("serverErrorHandler error : " + e.getMessage(), e);
			return "redirect:/500";
		}
	}
}